package com.chenjl.transport.support;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chenjl.transport.HookChannelHandler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
 * 用来执行解码、读取网络数据、进行业务处理
 * 2016-8-30 13:20:34
 * @author chenjinlong
 */
@Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {
	private static final Logger logger = LoggerFactory.getLogger(ServerHandler.class);
	private HookChannelHandler hookChannelHandler;
	private Map<String,Channel> channels = new ConcurrentHashMap<String,Channel>();

	public ServerHandler(HookChannelHandler hookChannelHandler) {
		this.hookChannelHandler = hookChannelHandler;
	}
	
	public Map<String, Channel> getChannels() {
		return channels;
	}
	
	//客户端接入
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.remoteAddress();
		
		channels.put(inetSocketAddress.toString(),channel);
		hookChannelHandler.channelActive(channel);
		logger.info("ServerHandler channelActive~~ 客户端接入 , address : {}",inetSocketAddress);
	}
	//客户端断开
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Channel channel = ctx.channel();
		InetSocketAddress inetSocketAddress = (InetSocketAddress) channel.remoteAddress();
		
		channels.remove(inetSocketAddress.toString());
		hookChannelHandler.channelInactive(channel);
		logger.info("ServerHandler channelInactive## 客户端断开, address : {}",inetSocketAddress);
	}
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("ServerHandler channel read begin ， 客户端有写入 , class : {}",msg.getClass());
		hookChannelHandler.channelRead(ctx.channel(),msg);
	}
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) throws Exception {
		logger.info("ServerHandler channel exceptionCaught ");
		
		hookChannelHandler.exceptionCaught(ctx.channel(),cause);
		cause.printStackTrace();
		ctx.close();
	}
}